package sc;

import java.awt.AWTKeyStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class FancyTextArea extends JTextArea implements FocusListener
{
	private static final long serialVersionUID = 1L;
	private static final Color focusedColour = new Color(255, 255, 0, 128);
	private static final Color unfocusedColour = new Color(255, 255, 255, 128);
	private JScrollPane scrollPane;
	private Color translucentColour;

	private class DocumentLimit extends PlainDocument
	{
		private static final long serialVersionUID = 1L;
		private int limit;

		DocumentLimit(int limit)
		{
			super();
			this.limit = limit;
		}

		public void insertString(int offset, String str, AttributeSet attr)
				throws BadLocationException
		{
			if (str == null)
				return;

			if ((getLength() + str.length()) > limit)
				str = str.substring(0, limit - getLength());

			super.insertString(offset, str, attr);
		}
	}

	FancyTextArea(int cols, int rows, int maxcharacters)
	{
		Set<AWTKeyStroke> forward = new HashSet<AWTKeyStroke>();
		forward.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0));
		Set<AWTKeyStroke> reverse = new HashSet<AWTKeyStroke>();
		reverse.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,
				KeyEvent.SHIFT_DOWN_MASK));

		setColumns(cols);
		setRows(rows);
		setDocument(new DocumentLimit(maxcharacters));

		setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
				forward);
		setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
				reverse);
		setFocusTraversalKeysEnabled(true);

		setOpaque(false);
		setLineWrap(true);
		addFocusListener(this);

		scrollPane = new JScrollPane(this);
		scrollPane.setOpaque(false);
		scrollPane.getViewport().setOpaque(false);
		
		translucentColour = unfocusedColour;
	}

	public JScrollPane getScrollPane()
	{
		return scrollPane;
	}

	public void paintComponent(Graphics g)
	{
		g.setColor(translucentColour);
		g.fillRect(0, 0, getWidth(), getHeight());
		super.paintComponent(g);
	}

	@Override
	public void focusGained(FocusEvent arg0)
	{
		translucentColour = focusedColour;
		repaint();
	}

	@Override
	public void focusLost(FocusEvent arg0)
	{
		translucentColour = unfocusedColour;
		repaint();
	}
}
